package com.xinchao.core.db;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@MapperScan(basePackages = {"com.xinchao.job.mapper.dmp"}, sqlSessionFactoryRef = "dmpSqlSessionFactory")
public class DmpDBConfig {

    @Autowired
    @Qualifier("dmpDS")
    private DataSource dmpDS;

    @Bean
    public SqlSessionFactory dmpSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dmpDS);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/mapper/dmp/*.xml"));
        return factoryBean.getObject();

    }

    @Bean
    public SqlSessionTemplate dmpSqlSessionTemplate() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(dmpSqlSessionFactory()); 
        return template;
    }

    /**
     * dmpDS数据源的事务控制
     * @param dataSource
     * @return
     */
    @Bean(name = "dmpTransactionManager")
    @Primary
    public PlatformTransactionManager testTransactionManager(@Qualifier("dmpDS") DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        return dataSourceTransactionManager;
    }

}
